package com.st.emps.util;

import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import com.st.emps.department.model.DepartmentModel;

public class FmtRequest {

	public static void write(Writer wr, String val) {
		try {
			wr.write(val);
			wr.flush();
			wr.close();
			wr = null;
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static void write(Writer wr, Object val) {
		if (val instanceof Collection<?>) {
			write(wr, new JSONArray(((Collection) val).toArray()).toString());
		} else if (val instanceof Map<?,?>) {
			write(wr, new JSONObject((Map<?,?>)val).toString());
		}
		else if (val instanceof String) {
			write(wr, val.toString());
			
		} else {
            if(val==null)
            	val="";
			write(wr, new JSONObject(val).toString());
		}

	}

	public static <T> T parseModel(HttpServletRequest request, Class<T> clazz) {
		T obj = null;
		try {
			obj = clazz.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		Map<String, String[]> map = request.getParameterMap();
		for (Entry<String, String[]> entry : map.entrySet()) {
			String name = entry.getKey();
			if ("action".equals(name))
				continue;
			String val = entry.getValue()[0];
			Field field;
			try {
				field = clazz.getDeclaredField(name);
				field.setAccessible(true);
				field.set(obj, val);
			} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return obj;
	}



	public static <T> T parseModel(HttpServletRequest request, Class<T> clazz,
			Map<String, String> fields) {
        T obj = null;
        try {
            obj = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e1) {
            e1.printStackTrace();
            return null;
        }
        for (Entry<String, String> entry : fields.entrySet()) {
            String value = request.getParameter(entry.getValue());
            String name = entry.getKey();
            try {
                Field field = clazz.getDeclaredField(name);
                field.setAccessible(true);
                field.set(obj, value);
            } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return obj;
	}
}
